import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { createDiscreteApi } from 'naive-ui'
const { message } = createDiscreteApi(['message'])

const instance = axios.create({
  baseURL: '',
  timeout: 300 * 1000,
  headers: {
    'Content-Type': 'application/json'
  }
})

instance.interceptors.request.use((config) => {
  return config
})

interface ApiResult<T> {
  code: number
  msg: string
  [key: string]: T | number | string
}

export default function request<T>(options: AxiosRequestConfig = {}) {
  return new Promise<T>((resolve, reject) => {
    instance(options)
      .then((response: AxiosResponse<ApiResult<T>>) => {
        if (typeof response.data === 'string') {
          const data = JSON.parse(response.data)
          const { code, msg } = data
          switch (code) {
            case 200:
              return resolve(data as T)
            default:
              if (msg) {
                message.error(msg)
              }
              return reject(data)
          }
        }
      })
      .catch((result) => {
        if (axios.isCancel(result)) {
          // 如果是取消请求导致的错误，不做额外的错误提示，直接返回
          return
        }
        reject(result)
      })
      .finally()
  })
}
